package com.example.ex.Controller;

import com.example.ex.entity.Message;
import com.example.ex.mapper.ChatMessageMapper;
import com.example.ex.mapper.LoginUserMapper;
import com.example.ex.pojo.ChatMessage;
import com.example.ex.pojo.LoginUser;
import com.example.ex.entity.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class MessageController {
    @Autowired
    ChatMessageMapper chatMessageMapper;

    @RequestMapping("/getRecord")
    public String getRecord(@RequestParam String senderName, @RequestParam String receiverName) {
        List<ChatMessage> history = chatMessageMapper.getRecord(senderName, receiverName);
        return convertToJson(history);

    }

    @RequestMapping("/getHistory")
    public String getHistory(@RequestParam String username) {
        List<String> history = chatMessageMapper.getHistory(username);
        return convertToJson(history);

    }


    private String convertToJson(List<?> objectList) {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = "";
        try {
            jsonString = objectMapper.writeValueAsString(objectList);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return jsonString;
    }

}